﻿using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace GerbilLib
{
    /// <summary>
    /// Checks whether an updated release for MediaGerbil is available on the
    /// CodePlex server. Useful if MediaGerbil was not installed using the
    /// ClickOnce installer but by extracting the archive.
    /// </summary>
    public class UpdateChecker
    {
        /// <summary>
        /// Retrieves the most recent recommended release for MediaGerbil.
        /// </summary>
        /// <returns>Version number of the recommended MediaGerbil release.</returns>
        public static string GetRecommendedRelease()
        {
            // Let's see how long this takes!
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            // Launch Codeplex web request
            HtmlWeb hw = new HtmlWeb();
            HtmlDocument doc = null;
            try
            {
                doc = hw.Load("http://mediagerbil.codeplex.com/releases/");
            }
            catch (Exception ex)
            {
                Logger.LogMessage(string.Format("UpdateChecker: An exception occurred while retrieving recommended release: {0}", ex.Message), LoggingLevel.Error);
                return null;
            }

            string recommendedVersion = string.Empty;

            // Extract meta data information
            HtmlNode releaseNode = doc.DocumentNode.SelectSingleNode("//a[@class='SelectedRelease']");
            recommendedVersion = GetRecommendedVersion(releaseNode.Attributes["title"].Value);

            // And we're done
            stopwatch.Stop();
            Logger.LogMessage(string.Format("UpdateChecker retrieved release information in {0:F} seconds.", stopwatch.ElapsedMilliseconds / 1000.0));
            return recommendedVersion;
        }

        /// <summary>
        /// Extracts the version number from the recommended release string.
        /// </summary>
        /// <param name="text">Recommended release text from CodePlex</param>
        /// <returns>Version number of the recommended release</returns>
        private static string GetRecommendedVersion(string text)
        {
            Regex rex = new Regex(@".*(?<Version>\d+.\d+.\d+)");
            GroupCollection gc = rex.Match(text).Groups;
            return gc["Version"].Value;
        }
    }
}
